package com.shj.config.security;

import com.shj.entity.SysMenu;
import com.shj.entity.SysRoleMenu;
import com.shj.service.SysMenuService;
import com.shj.service.SysRoleMenuService;
import com.shj.service.impl.SysMenuServiceImpl;
import com.shj.service.impl.SysRoleMenuServiceImpl;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 自定义权限资源过滤器，实现动态的权限验证
 * 它的主要责任就是当访问一个url时，返回这个url所需要的访问权限
 * @Author songhuajian
 * @Date 2020/1/12 23:26
 **/
@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysRoleMenuService sysRoleMenuService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * @description 返回本次访问需要的权限
     * @author songhuajian
     * @date 2020/1/12 23:30
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        // 正则匹配？之前的真实url
        String pattern = ".*(?=\\?)";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(requestUrl);
        if (m.find()) {
            requestUrl = m.group(0);
        }

        //根据请求路径查询权限id
        SysMenu sysMenu = sysMenuService.findByPath(requestUrl);
        //根据权限id查询角色id
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        if (sysMenu != null){
            list = sysRoleMenuService.findByPowerId(sysMenu.getMenuId());
        }
        int size = list.size();

        if (list != null && size >0){
            String[] values = new String[size];
            for (int i=0;i<size;i++){
                values[i] = list.get(i).getRoleId();
            }
            return SecurityConfig.createList(values);
        }

        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
